package com.pk.platform.util.filter;

import java.util.Map;

import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.apache.struts2.json.JSONResult;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.pk.platform.util.GlobalLoader;
import com.pk.platform.util.constant.Constant;

public class ActionDebugInterceptor implements Interceptor {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init() {
		// TODO Auto-generated method stub

	}

	public String intercept(ActionInvocation invocation) throws Exception {
		String isDebug = (String)GlobalLoader.getContext().getAttribute(Constant.IS_DEBUG);
		if(Constant.N.equals(isDebug))
		{
			final String resultCode = invocation.invoke();
			return resultCode;
		}
		else
		{
			System.out.println("-----------Action运行之前...begin-----------");
			String actionName = invocation.getAction().getClass().getName();
			int index = actionName.indexOf("$$");
			if (index > -1) {
				actionName = actionName.substring(0, index);
			}
			System.out.println("被调用的Action为:" + actionName);
			ActionProxy proxy = invocation.getProxy();
			ActionConfig config = proxy.getConfig();
			System.out.println("被调用的method为:" + config.getMethodName());
			System.out.println("传给action的参数为:");
			// 这个对象就是request.parameters
			Map<String, Object> parameters = invocation.getInvocationContext().getParameters();
			for (String key : parameters.keySet()) {
				String[] params = (String[]) parameters.get(key);
				StringBuffer buffer = new StringBuffer();
				for (String param : params) {
					buffer.append("," + param);
				}
				String paramValue = buffer.toString();
				paramValue = paramValue.substring(1);
				System.out.println("\t" + key + "=" + paramValue);
			}
			final String resultCode = invocation.invoke();
			if(!"file".equals(resultCode))
			{
				try
				{
					if(invocation.getResult() instanceof JSONResult)
					{
						System.out.println("json result");
					}
					else if(invocation.getResult() instanceof StrutsResultSupport)
					{
						StrutsResultSupport result = (StrutsResultSupport)invocation.getResult();
						if (result != null) {
							System.out.println("转到的jsp页面:" + result.getLocation());
						}
						System.out.println("-----------Action运行之后...end-----------\n");
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			return resultCode;
		}
	}

}
